package com.tianji.learning.mq;

import com.tianji.common.utils.JsonUtils;
import com.tianji.learning.domain.dto.ComboWriteDTO;
import com.tianji.learning.mapper.LearningMapper;
import com.tianji.learning.mapper.LearningRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @Author whx
 * @Date 2024/11/28 15:23
 */
@Component
@Slf4j
public class LearningListener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private LearningRecordMapper learningRecordMapper;

    @Autowired
    private LearningMapper learningMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.queue"),
            exchange = @Exchange(name = "dl.exchange", delayed = "true"),
            key = "dl.key"
    ))
    public void comboWriteListener(ComboWriteDTO comboWriteDTO){
        log.info("延迟队列接收到消息！！！");
        // 20s之后，查看redis 比较数据
        String newJsonStr = (String) redisTemplate.opsForHash().get(
                "lessonId:" + comboWriteDTO.getLessonId().toString(),
                "sectionId:" + comboWriteDTO.getSectionId()
        );

        String oldJsonStr = comboWriteDTO.getJsonStr();

        ComboWriteDTO dto1 = JsonUtils.toBean(newJsonStr, ComboWriteDTO.class);
        ComboWriteDTO dto2 = JsonUtils.toBean(oldJsonStr, ComboWriteDTO.class);

        if (dto1.equals(dto2)) {
            // 相等，说明没更新，写入数据库
            // 更新lr（moment）
            learningRecordMapper.updateLR(dto1.getMoment(), dto1.getId());

            // 更新ll（latest， last）
            learningMapper.updateLL(comboWriteDTO.getLessonId(), comboWriteDTO.getSectionId());
        }

        // 不相等，无操作


    }

}
